package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping("/user/login")
    public String doLogin(User user, Map<String, Object> map, HttpSession
            session) {
        User byUserNameAndPassword = userService.getByUserNameAndPassword(user);
        if (byUserNameAndPassword != null ) { //可以登录
            session.setAttribute("loginUser", byUserNameAndPassword);
            log.info("登录成功，用户名：" + byUserNameAndPassword.getUsername());
          // 防止重复提交使用重定向
            return "redirect:/main.html";
        } else {
            map.put("msg", "用户名或密码错误");
            log.error("登录失败");
            return "login";
        }
    }


    @RequestMapping("/user/logout")
    public String doLogout(HttpSession session){

        //清空session的login.User
        session.removeAttribute("loginUser");
        return "login";//跳转页面得到登录页面

    }
}